package com.ncr.teradata.bireport;

import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.DriverManager;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * DBFactory.java
 * 数据库静态工厂类
 *
 * @author ylpeng
 * @date Dec 19, 2006
 *
 * @modify date,auther,desc
 */
public class DBFactory
{
	//上下文环境
	private static Context context = null;
	
	//CONTEXT数据源
	private static DataSource ctxds = null;
	
	//DBCP数据源
	private static BasicDataSource dbcpds = null;
	
	//初始化数据源
	static{
		try{
			if (InitParam.DB_CONNECTION_MODE.equals("1")){
				dbcpds = new BasicDataSource();
				dbcpds.setDriverClassName(InitParam.DB_DRIVER);
				dbcpds.setUrl(InitParam.DB_URL);
				dbcpds.setUsername(InitParam.DB_USERNAME);
				dbcpds.setPassword(InitParam.DB_PASSWORD);
				dbcpds.setMaxActive(50);
			}
			else if (InitParam.DB_CONNECTION_MODE.equals("2")){
				context = new InitialContext();
				ctxds = (DataSource)context.lookup(InitParam.DB_DATASOURCE_NAME);
			}
			else if (InitParam.DB_CONNECTION_MODE.equals("3")){
				Class.forName(InitParam.DB_DRIVER);
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
 	 *从连接池中取出一个数据库连接对象
 	 *
 	 *@return Connection 返回的数据库连接对象
 	 */
	public static Connection getConnection(){
		try{
			if (InitParam.DB_CONNECTION_MODE.equals("1"))
				return dbcpds.getConnection();
			else if (InitParam.DB_CONNECTION_MODE.equals("2"))
				return ctxds.getConnection();
			else if (InitParam.DB_CONNECTION_MODE.equals("3"))
				return DriverManager.getConnection(InitParam.DB_URL,InitParam.DB_USERNAME,InitParam.DB_PASSWORD);;
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return null;
	}
	
	/**
 	 *关闭数据库连接
 	 *
 	 *@param conn Connection 需要关闭的数据库连接对象
 	 */
	public static void close(Connection conn){
		try{
			if(conn != null)
				conn.close();
		}
		catch(Exception e){
			e.printStackTrace();	
		}
	}
	
	/**
     *创建数据库查询对象
     *
     *@return DBQuery 返回数据库查询对象
     */
	public static DBQuery getDBQuery(){
		return new DBQuery();
	}
	
	/**
     *创建数据库更新对象
     *
     *@return DBUpdate 返回数据库更新对象
     */
	public static DBUpdate getDBUpdate(){
		return new DBUpdate();
	}
}